package com.jt.www.biz.order_pc.controller;

import com.jt.www.biz.order_pc.service.InsService;
import com.jt.www.domain.qo.InsParamVo;
import com.jt.www.enums.issue.AppStatusEnum;
import com.jt.www.enums.issue.FinanceStatusEnum;
import com.jt.www.model.remote.ins.InsResultVO;
import com.jt.www.model.reps.RemoteResultDTO;
import com.jt.www.model.reps.ResponseData;
import com.jt.www.util.DateUtils;
import com.jt.www.util.JsonUtil;
import com.jt.www.util.excel.CsvExportUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.*;

/**
 * @author admin_ltf
 * @create 2019-05-09 13:52
 */
@Api(value = "远程调用投保中心接口", tags = {"REMOTE-INS-INFO-API"}, description = "远程调用投保中心接口")
@RestController
@RequestMapping(value = "/remote/ins")
public class InsController {

    public static final Logger log = LoggerFactory.getLogger(InsController.class);

    @Autowired
    private InsService insService;

    @ApiOperation(value = "查询保单列表", notes = "查询保单列表", httpMethod = "POST")
    @PostMapping(value = "/searchInsuranceList")
    public ResponseData searchInsuranceList(@RequestBody String insParamVo) {
        // 应前端要求 ，后端只需要将参数转发即可  不做处理，  远程接口 接受的是一个String类型的json字符串  。所以 该参数是一个String
        ResponseData resultDTO = insService.searchInsuranceList(insParamVo);
        return resultDTO;
    }

    @ApiOperation(value = "查询我学保保单列表", notes = "查询我学保保单列表", httpMethod = "POST")
    @PostMapping(value = "/searchWxbAppList")
    public RemoteResultDTO<List<InsResultVO>> searchWxbAppList(@RequestBody String insParamVo) {
        // 应前端要求 ，后端只需要将参数转发即可  不做处理，  远程接口 接受的是一个String类型的json字符串  。所以 该参数是一个String
        RemoteResultDTO resultDTO = insService.searchWxbAppList(insParamVo);
        return resultDTO;
    }

    @ApiOperation(value = "获取系统当前时间", notes = "获取系统当前时间", httpMethod = "GET")
    @GetMapping(value = "/getCurrentTime")
    public String getCurrentTime() {
        String currentTime = DateUtils.conver(new Date(), DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
        return currentTime;
    }

    @ApiOperation(value = "获取待支付/保障中保单数量", notes = "获取待支付/保障中保单数量", httpMethod = "GET")
    @GetMapping(value = "/countAppNumByStatus", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity countAppNumByStatus(@RequestParam(value = "", required = true) String userCode) throws Exception {
        return insService.countAppNumByStatus(userCode);
    }

    /**
     * 业务端导出投保单信息
     *
     * @param response
     * @param insParamVo
     */
    @ApiOperation(value = "业务端导出投保单信息", notes = "业务端导出投保单信息")
    @GetMapping(value = "/exportInsuranceList")
    public void exportInsuranceList(HttpServletResponse response, InsParamVo insParamVo) {
        try {

            String findCode = "exportInsuranceList_" + System.currentTimeMillis();

            log.info("{} 业务端导出投保单信息 入参：insParamVo->{}", findCode, insParamVo);

            // 查询需要导出的数据
            ResponseData resultDTO = insService.searchInsuranceList(JsonUtil.object2Json(insParamVo));
            List<InsResultVO> list = resultDTO.getList();

            // 构造导出数据结构
            String titles = "序号,保单号,投保单号,投保时间,订单号,产品名称,保险起期,保险止期,被保险人名称,被保人人数,保费,财务状态,投保单状态";  // 设置表头
            String keys = "serialNo,policyNo,appCode,applicationDate,orderCode,productName,polStartDate,polEndDate,insuredName,insuredStudentNum,afterPrem,financeStatus,appStatus";  // 设置每列字段

            // 构造导出数据
            List<Map<String, Object>> datas = new ArrayList<>();
            Map<String, Object> map = null;

            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {

                    int insuredNumber = 0;
                    if (StringUtils.isNotBlank(list.get(i).getInsuredStudentNum())) {
                        insuredNumber += Integer.valueOf(list.get(i).getInsuredStudentNum());
                    }
                    if (StringUtils.isNotBlank(list.get(i).getInsuredTeacherNum())) {
                        insuredNumber += Integer.valueOf(list.get(i).getInsuredTeacherNum());
                    }

                    map = new HashMap<>();
                    map.put("serialNo", i + 1);
                    map.put("policyNo", StringUtils.isNotBlank(list.get(i).getPolicyNo()) ? list.get(i).getPolicyNo() + "\t" : "");
                    map.put("appCode", list.get(i).getAppCode());
                    map.put("applicationDate", list.get(i).getApplicationDate());
                    map.put("orderCode", list.get(i).getOrderCode());
                    map.put("productName", list.get(i).getProductName());
                    map.put("polStartDate", list.get(i).getPolStartDate());
                    map.put("polEndDate", list.get(i).getPolEndDate());
                    map.put("insuredName", list.get(i).getInsuredName());
                    map.put("insuredStudentNum", insuredNumber);
                    map.put("afterPrem", list.get(i).getAfterPrem());
                    map.put("financeStatus", FinanceStatusEnum.getEnumByCode(list.get(i).getFinanceStatus()).getDesc());
                    map.put("appStatus", AppStatusEnum.getEnumByCode(list.get(i).getAppStatus()).getDesc());

                    datas.add(map);
                }
            }

            // 设置导出文件前缀
            String fName = "保单列表_";

            // 文件导出
            OutputStream os = response.getOutputStream();
            CsvExportUtil.responseSetProperties(fName, response);
            CsvExportUtil.doExport(datas, titles, keys, os);
            os.close();
        } catch (Exception e) {
            log.error("业务端保单列表 导出失败" + e.getMessage(), e);
        }
    }
}
